﻿using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SendMailServer.Jike
{
    internal class CAPGetter
    {
        private string capDir = "D:\\agcimDesktopFiles\\installationPackage\\综合应用平台";
        public CAPGetter() {
        }
        public ResMsg LoadCAPFile(string key)
        {
            if (key != "GetCAPFileList")
            {
                return null;
            }
            var files = new DirectoryInfo(capDir).GetFiles("*.zip", SearchOption.AllDirectories);
            StringBuilder stringBuilder = new StringBuilder();
            for (var i = 0; i < files.Length; i++)
            {
                if (stringBuilder.Length > 0)
                {
                    stringBuilder.Append(",");
                }
                var relativePath = files[i].FullName.Substring(capDir.Length).Trim(new char[] { '/', '\\' });
                var createTime = files[i].CreationTime;
                stringBuilder.Append(relativePath);
                stringBuilder.Append("*");
                stringBuilder.Append(createTime);
                stringBuilder.Append("*");
                var desFile = Path.ChangeExtension(files[i].FullName, ".txt");
                if (File.Exists(desFile))
                {
                    stringBuilder.Append(File.ReadAllText(desFile));
                }
                else
                {
                    stringBuilder.Append("暂无描述");
                }
            }
            return new ResMsg()
            {
                MsgCode = key,
                IsOk = true,
                Content = stringBuilder.ToString(),
                UseSelfResponse = true
            };
        }
        public ResMsg DeployCAPFile(string key,string capFileName)
        {
            try
            {
                if (key != "DeployCAPFile")
                {
                    return null;
                }
                if (capFileName.EndsWith(",desktop"))
                {
                    capFileName = capFileName.Substring(0, capFileName.Length - ",desktop".Length);
                }
                var file = Path.Combine(capDir, capFileName);
                var mainDirName= capFileName.Substring(0, capFileName.IndexOf('.') > 0 ? capFileName.IndexOf('.') : capFileName.Length);
                if (capFileName.IndexOf('-') > 0)
                {
                    mainDirName = capFileName.Substring(0, capFileName.IndexOf('-') > 0 ? capFileName.IndexOf('-') : capFileName.Length);
                }

                
                var targetDir = @"D:\nginx-1.16.1\html\" + mainDirName;
                if(Directory.Exists(targetDir)==false)
                {
                    Directory.CreateDirectory(targetDir);
                }
                var capInfo = Path.Combine(targetDir, "cap.info");
                var currentApplication = File.Exists(capInfo) ? File.ReadAllText(capInfo) : "";
                if (currentApplication != capFileName && File.Exists(file))
                {
                    Directory.Delete(targetDir, true);
                    ExtractFile(file, targetDir);
                    File.WriteAllText(capInfo, capFileName);
                }
                return new ResMsg()
                {
                    MsgCode = key,
                    IsOk = true,
                    Content = mainDirName,
                    UseSelfResponse = true
                };
            }
            catch (Exception err)
            {
                return new ResMsg()
                {
                    MsgCode = key,
                    IsOk = false,
                    Content = "发布"+capFileName+"失败，因为"+err.Message,
                    UseSelfResponse = true
                };
            }
        }

        public void ExtractFile(string zipFile, string extractPath)
        {
            if (File.Exists(zipFile) == false)
            {
                return;
            }
            // 打开zip文件
            using (ZipArchive archive = ZipFile.OpenRead(zipFile))
            {
                // 遍历zip文件中的每个文件
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    // 创建文件保存路径
                    string fullPath = Path.Combine(extractPath, entry.FullName);

                    // 创建文件夹
                    if (entry.FullName.EndsWith("/"))
                    {
                        Directory.CreateDirectory(fullPath);
                        continue;
                    }
                    var dir = Path.GetDirectoryName(fullPath);
                    if (Directory.Exists(dir) == false)
                    {
                        Directory.CreateDirectory(dir);
                    }
                    // 创建文件流
                    using (FileStream fileStream = new FileStream(fullPath, FileMode.Create))
                    {
                        // 复制zip文件的流到文件流中
                        using (Stream stream = entry.Open())
                        {
                            stream.CopyTo(fileStream);
                        }
                    }
                }
            }
        }
    }
}
